package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder() {
        log.info("处理支付超时订单：{}", new Date());
        //查询过去15分钟的没有付款的订单，设置支付超时处理
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        //执行查询订单列表
        List<Orders> ordertimeLT = orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, localDateTime);
        //修改状态
        if (ordertimeLT != null && ordertimeLT.size() != 0) {
            ordertimeLT.stream().forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            });
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        log.info("处理派送中超时订单：{}", new Date());
        //查询过去一个小时前的状态为派送中的订单列表，设置已完成状态
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        //查询订单列表
        List<Orders> ordertimeLT = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        //修改状态
        if (ordertimeLT != null && ordertimeLT.size()>0){
            ordertimeLT.stream().forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }
    }
}
